package logic

import (
	"gitee.com/DonHz/qimi/bluebell/dao/mysql"
	"gitee.com/DonHz/qimi/bluebell/dao/redis"
	"gitee.com/DonHz/qimi/bluebell/models"
	"gitee.com/DonHz/qimi/bluebell/util/snowflake"
	"time"
)

func CreateArticle(req *models.PostArticle) (err error) {
	now:=time.Now().UnixMilli()
	art := &models.Article{
		CommunityId: req.CommunityId,
		CreateTime: now,
		UpdateTime: now,
		Status:req.Status,
		Title:req.Title,
		Content:req.Content,
		AuthorId: req.AuthorId,
	}
	art.ArticleId= snowflake.GenID()
	err = mysql.CreateArticle(art)
	if err!=nil {
		return err
	}
	err = redis.CreateArticle(art.ArticleId)
	return err
}

func GetArticleById(aid int64) (data *models.ApiArticleDetail, err error) {
	article, err:= mysql.GetArticleById(aid)
	if err!=nil {
		return
	}
	authorName, err:=mysql.FindUserById(article.AuthorId)
	if err!=nil {
		return
	}
	community, err:=mysql.GetCommunityById(article.CommunityId)
	if err!=nil {
		return
	}
	data = &models.ApiArticleDetail{
		AuthorName: authorName,
		Article: article,
		Community:community,
	}
	return
}

func GetArticleList() (data []*models.ApiArticleDetail, err error) {
	articles, err:= mysql.GetArticleList()
	if err!=nil {
		return
	}
	data = make([]*models.ApiArticleDetail, 0, len(articles))
	for _, article:= range articles {
		authorName, err:=mysql.FindUserById(article.AuthorId)
		if err!=nil {
			continue
		}
		community, err:=mysql.GetCommunityById(article.CommunityId)
		if err!=nil {
			continue
		}
		data = append(data, &models.ApiArticleDetail{
			AuthorName: authorName,
			Article: &article,
			Community:community,
		})
	}
	return
}